package com.snts.synchronization.transaction;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.snts.synchronization.core.Change;
import com.snts.synchronization.core.UUID;

/*
 * Note: this class has a natural ordering that is
 * inconsistent with equals.
 */

public class Transaction implements Comparable<Transaction> {

	private UUID id;
	private Date endTime;
	private List<Change> changes = new ArrayList<Change>();
	private boolean sorted = false;
	
	public Transaction(UUID id) {
		super();
		this.id = id;
	}
	
	public UUID getId() {
		return id;
	}

	public Date getEndTime() {
		return endTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

	public List<Change> getChanges(){
		sortChanges();
		return new ArrayList<Change>(changes);
	}
	
	private void sortChanges(){
		if(!sorted){
			Collections.sort(changes, new Comparator<Change>(){
				@Override
				public int compare(Change o1, Change o2) {
					return (int) (o1.getTime().getTime() - o2.getTime().getTime());
				}
			});
			sorted = true;
		}
	}

	public void addChange(Change change){
		if(! id.equals(change.getTransactionId())){
			throw new IllegalArgumentException("Change " + change + " doesn't belong to transaction " + this);
		}
		if(change.getTime().getTime() > endTime.getTime()){
			//endTime = change.getTime();
		}
		changes.add(change);
		sorted = false;
	}

	@Override
	public int compareTo(Transaction t) {
		return (int) (endTime.getTime() - t.endTime.getTime());
	}

}
